import router from './routers'
import { UserStore } from "@/store/modules/user";
import { PermissionStore } from "@/store/modules/permission";
import { ElNotification, ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken,getPostId } from '@/utils/auth'
import { isRelogin } from '@/utils/request'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login']
// console.log(userStore,'userStore')
// 解决3级菜单keep-alive失效问题
// router.beforeResolve((to, from, next) => {
//   if (to.matched && to.matched.length > 2) {
//     to.matched.splice(1, to.matched.length - 2)
//   }
//   next();
// })
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
     const userStore = UserStore();
     const permissionStore = PermissionStore();
      if (userStore.roles.length === 0) {
        isRelogin.show = true
        // 判断当前用户是否已拉取完user_info信息
        userStore.GetInfo().then(res => {
          // const postId =res.postList[0].id;
          const postId =getPostId(); 
          isRelogin.show = false
          permissionStore.GenerateRoutes(postId).then(accessRoutes => {
            // 根据roles权限生成可访问的路由表
            accessRoutes.forEach(itemRouter => {
              router.addRoute(itemRouter) // 动态添加可访问路由表
            })
            // 4.最后添加 notFoundRouter
            router.addRoute({ path: '/:pathMatch(.*)*', redirect: '/404', hidden: true });
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          })
         
        }).catch(err => {
          console.log("路由拦截");
          const userStore = UserStore();
          userStore.LogOut().then(() => {
              ElMessage.error(err)
              next({ path: '/' })
            })
          })
  
      } else {
        console.log(to,'to')
        if (to.matched.length !== 0) {
          next()
        } else {
          next({ path: '/404' })
        }
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
